<template>
  <view class="bg-white flex flex-col h-auto">
    <nav-bar :title="navconfig.title" color="white" bg-color="#111827" show-back></nav-bar>
    <view class="content p-20rpx flex-auto h-full">
      <view>
        <view class="my-5rpx w-full form-item flex justify-start">
          <u-button
            @click="openDishesTemplatePopup"
            icon="plus-circle-fill"
            type="primary"
            size="large"
            custom-style="padding:10rpx;width: fit-content; margin-left: 20rpx;font-size: 10rpx;"
            >从平台菜品选择</u-button
          >
        </view>
      </view>
      <u-line margin="0.5em 0" />
      <u-row gutter="10rpx" custom-style="flex:auto;align-items: baseline;">
        <u-col span="12">
          <u-form
            ref="refForm"
            :model="formData"
            :rules="formRules"
            label-width="70rpx"
            :label-style="{ fontSize: '10rpx' }"
            label-position="left"
          >
            <view class="flex justify-start">
              <u-form-item label="类别:" prop="foodTypeName" required>
                <view class="my-5rpx w-full form-item">
                  <uni-data-select
                    v-model="formData.foodTypeId"
                    :localdata="foodTypeList"
                    :clear="false"
                    @change="selectType"
                  ></uni-data-select>
                  <!-- <u-input v-model="formData.foodTypeName" placeholder="请输入" font-size="10rpx"></u-input> -->
                </view>
              </u-form-item>
              <u-form-item> </u-form-item>
            </view>
            <view class="flex justify-start">
              <u-form-item label="菜品名称:" prop="name" required>
                <view class="my-5rpx w-full form-item">
                  <u-input v-model="formData.name" placeholder="请输入" font-size="10rpx"></u-input>
                </view>
              </u-form-item>
              <u-form-item label="原价:" prop="price" required>
                <view class="w-full form-item">
                  <u-input type="digit" v-model="formData.price" font-size="10rpx"></u-input>
                </view>
              </u-form-item>
            </view>

            <view class="flex justify-start flex-col">
              <u-form-item label="价格:" label-position="top">
                <view class="w-full form-item">
                  <uni-table
                    :loading="pageStatus.loading"
                    class="table-height"
                    stripe
                    emptyText="暂无更多数据"
                    :border="true"
                  >
                    <!-- 表头行 -->
                    <uni-tr class="thead-tr">
                      <uni-th align="center" class="fixed-left">
                        <view class="kui-color-theme-bg p-5rpx w-fit rounded-full inline-block">
                          <u-icon name="plus" color="white" size="8rpx" @click="showPricePopup"></u-icon>
                        </view>
                      </uni-th>
                      <uni-th align="center">价格</uni-th>
                      <uni-th align="center">人员类型</uni-th>
                      <uni-th align="center">客户类别</uni-th>
                      <uni-th align="center">卡类别</uni-th>
                      <uni-th align="center">操作</uni-th>
                    </uni-tr>
                    <!-- 表格数据行 -->
                    <uni-tr v-for="(item, index) in formData.priceItem" :key="index">
                      <uni-td align="center" class="fixed-left">{{ index + 1 }}</uni-td>

                      <uni-td align="center">{{ item.price }}</uni-td>
                      <uni-td align="center">{{
                        getFieldValueByDatacom(item.customerTypeId, customerTypeList)
                      }}</uni-td>
                      <uni-td align="center">{{
                        getFieldValueByDatacom(item.customerCategoryId, customerTypeSmbelList)
                      }}</uni-td>
                      <uni-td align="center">{{ getFieldValueByDatacom(item.cardType, cardTypeList) }}</uni-td>
                      <uni-td align="center">
                        <view class="bg-red-500 p-3rpx w-fit rounded-full inline-block">
                          <u-icon name="trash" color="white" size="10rpx" @click="delPrice(item, index)"></u-icon>
                        </view>
                      </uni-td>
                    </uni-tr>
                  </uni-table>
                </view>
              </u-form-item>
              <!-- 计算原料数据 -->
              <view class="flex text-base mt-10rpx total-bar">
                <view class="mr-20rpx">
                  <text>热量（千卡）：</text>
                  <text>{{ totalData.totalHeat }}</text>
                </view>
                <view class="mr-20rpx">
                  <text>蛋白质（g）：</text>
                  <text>{{ totalData.totalProtein }}</text>
                </view>
                <view class="mr-20rpx">
                  <text>脂肪（g）：</text>
                  <text>{{ totalData.totalFat }}</text>
                </view>
                <view class="mr-20rpx">
                  <text>淡水化合物（g）：</text>
                  <text>{{ totalData.totalCarbohydrate }}</text>
                </view>
              </view>
            </view>

            <view class="flex justify-start">
              <u-form-item label="辣味:" prop="spicy">
                <view class="my-5rpx w-full form-item">
                  <uni-data-select
                    v-model="formData.spicy"
                    :localdata="formatDictData(dicts['sys_spicy'], false)"
                    :clear="false"
                  ></uni-data-select>
                </view>
              </u-form-item>
              <u-form-item label="口感:" prop="texture">
                <view class="w-full form-item">
                  <uni-data-select
                    v-model="formData.texture"
                    :localdata="formatDictData(dicts['sys_texture'], false)"
                    :clear="false"
                  ></uni-data-select>
                </view>
              </u-form-item>
            </view>
            <view class="flex justify-start">
              <u-form-item label="口味:" prop="flavor">
                <view class="my-5rpx w-full form-item">
                  <uni-data-select
                    v-model="formData.flavor"
                    :localdata="formatDictData(dicts['sys_flavor'], false)"
                    :clear="false"
                  ></uni-data-select>
                </view>
              </u-form-item>
              <u-form-item label="推荐:" prop="recommend">
                <view class="w-full form-item">
                  <u-radio-group v-model="formData.recommend" active-color="var(--kui-color-theme)">
                    <u-radio
                      :label="item.label"
                      :name="item.value"
                      v-for="item in dataSource.yeasOrNo"
                      :key="item.value"
                      label-size="10rpx"
                      size="10rpx"
                    ></u-radio>
                  </u-radio-group>
                </view>
              </u-form-item>
            </view>
            <view class="flex justify-start">
              <u-form-item label="会员折扣:" prop="memberDiscount">
                <view class="w-full form-item">
                  <u-radio-group v-model="formData.memberDiscount" active-color="var(--kui-color-theme)">
                    <u-radio
                      :label="item.label"
                      :name="item.value"
                      v-for="item in dataSource.yeasOrNo"
                      :key="item.value"
                      label-size="10rpx"
                      size="10rpx"
                    ></u-radio>
                  </u-radio-group>
                </view>
              </u-form-item>
              <u-form-item label="前台打票:" prop="frontDeskPrinting">
                <view class="w-full form-item">
                  <u-radio-group v-model="formData.frontDeskPrinting" active-color="var(--kui-color-theme)">
                    <u-radio
                      :label="item.label"
                      :name="item.value"
                      v-for="(item, index) in dataSource.yeasOrNo"
                      :key="item.index"
                      label-size="10rpx"
                      size="10rpx"
                    ></u-radio>
                  </u-radio-group>
                </view>
              </u-form-item>
            </view>

            <view class="flex justify-start">
              <u-form-item label="后厨打票:" prop="rearKitchenPrinting">
                <view class="w-full form-item">
                  <u-radio-group v-model="formData.rearKitchenPrinting" active-color="var(--kui-color-theme)">
                    <u-radio
                      :label="item.label"
                      :name="item.value"
                      v-for="item in dataSource.yeasOrNo"
                      :key="item.value"
                      label-size="10rpx"
                      size="10rpx"
                    ></u-radio>
                  </u-radio-group>
                </view>
              </u-form-item>
            </view>
            <view class="flex justify-start flex-col">
              <u-form-item label="原料:" label-position="top">
                <view class="w-full form-item">
                  <uni-table
                    :loading="pageStatus.loading"
                    class="table-height"
                    stripe
                    emptyText="暂无更多数据"
                    :border="true"
                  >
                    <!-- 表头行 -->
                    <uni-tr class="thead-tr">
                      <uni-th align="center" class="fixed-left">
                        <view class="kui-color-theme-bg p-5rpx w-fit rounded-full inline-block">
                          <u-icon name="plus" color="white" size="8rpx" @click="showPopup"></u-icon>
                        </view>
                      </uni-th>
                      <uni-th align="center">名称</uni-th>
                      <uni-th align="center">热量（千卡）</uni-th>
                      <uni-th align="center">蛋白质（g）</uni-th>
                      <uni-th align="center">脂肪（g）</uni-th>
                      <uni-th align="center">淡水化合物（g）</uni-th>
                      <uni-th align="center">操作</uni-th>
                    </uni-tr>
                    <!-- 表格数据行 -->
                    <uni-tr v-for="(item, index) in formData.materialRecipeLevelEntityList" :key="item.buffetOrderId">
                      <uni-td align="center" class="fixed-left"
                        ><text class="text-gray-400">{{ index + 1 }}</text>
                      </uni-td>
                      <uni-td align="center">{{ item.name }}</uni-td>
                      <uni-td align="center">{{ item.quantityHeat }}</uni-td>
                      <uni-td align="center">{{ item.protein }}</uni-td>
                      <uni-td align="center">{{ item.fat || "-" }}</uni-td>
                      <uni-td align="center">{{ item.carbohydrate }}</uni-td>
                      <uni-td align="center">
                        <view class="bg-red-500 p-3rpx w-fit rounded-full inline-block">
                          <u-icon name="trash" color="white" size="10rpx" @click="delSource(item, index)"></u-icon>
                        </view>
                      </uni-td>
                    </uni-tr>
                  </uni-table>
                </view>
              </u-form-item>
              <!-- 计算原料数据 -->
              <view class="flex text-base mt-10rpx total-bar">
                <view class="mr-20rpx">
                  <text>热量（千卡）：</text>
                  <text>{{ totalData.totalHeat }}</text>
                </view>
                <view class="mr-20rpx">
                  <text>蛋白质（g）：</text>
                  <text>{{ totalData.totalProtein }}</text>
                </view>
                <view class="mr-20rpx">
                  <text>脂肪（g）：</text>
                  <text>{{ totalData.totalFat }}</text>
                </view>
                <view class="mr-20rpx">
                  <text>淡水化合物（g）：</text>
                  <text>{{ totalData.totalCarbohydrate }}</text>
                </view>
              </view>
            </view>

            <u-form-item label="禁忌人群:" prop="tabooPopulation">
              <view class="w-full form-item">
                <u-checkbox-group @change="onTabooPopulationChange">
                  <u-checkbox
                    v-for="(taboo, index) in dicts['sys_tabooPopulation']"
                    :key="index"
                    :label="taboo.dictValue"
                    :name="taboo.dictValue"
                    :checked="hasTaboo(taboo.dictValue)"
                    active-color="var(--kui-color-theme)"
                  >
                  </u-checkbox>
                </u-checkbox-group>
              </view>
            </u-form-item>
            <u-form-item label="食材说明:" prop="introcetion">
              <view class="w-full form-item">
                <u-textarea v-model="formData.introcetion" placeholder="介绍、食物说明"></u-textarea>
              </view>
            </u-form-item>
            <view class="flex justify-start">
              <u-form-item label="功效:" prop="effect">
                <view class="my-5rpx w-full form-item">
                  <uni-data-select
                    v-model="formData.effect"
                    :localdata="formatDictData(dicts['sys_effect_food'], false)"
                    :clear="false"
                  ></uni-data-select>
                </view>
              </u-form-item>
              <u-form-item label="烹饪方法:" prop="cookingMethods">
                <view class="w-full form-item">
                  <uni-data-select
                    v-model="formData.cookingMethods"
                    :localdata="formatDictData(dicts['sys_cookingMethods_food'], false)"
                    :clear="false"
                  ></uni-data-select>
                </view>
              </u-form-item>
            </view>
            <view class="flex justify-start">
              <u-form-item label="单位:" prop="unit">
                <view class="w-full form-item">
                  <uni-data-select
                    v-model="formData.unit"
                    :localdata="formatDictData(dicts['sys_unit_food'], false)"
                    :clear="false"
                  ></uni-data-select>
                </view>
              </u-form-item>
              <view class="flex-1"></view>
            </view>
            <u-form-item label="菜品图片:" prop="photo">
              <view class="w-fit form-item justify-start flex-none">
                <!-- <kui-upload-img
                  action="/kingon-file/oss/endpoint/put-file?code=minio"
                  :maxFileNumber="3"
                  imgMod="scaleToFill"
                  :autoUpload="true"
                  @change="onFileChange"
                  ref="uploadImg"
                >
                </kui-upload-img> -->
                <u-upload
                  :file-list="uploadFileList"
                  width="100rpx"
                  height="100rpx"
                  :max-count="1"
                  @delete="delImg"
                  @after-read="afterRead"
                ></u-upload>
                <!-- <u-image :src="formData.photo" mode="aspectFill" width="100rpx" height="100rpx" radius="5rpx"></u-image> -->
              </view>
            </u-form-item>
          </u-form></u-col
        >
      </u-row>

      <view class="w-100rpx m-auto"><u-button @click="confirmData" type="primary">保存</u-button></view>
    </view>

    <!-- 原料选择弹窗 -->
    <select-popup ref="refSelectPopup" @confirm="onAddSource"></select-popup>

    <!-- 添加特殊价格弹窗 -->
    <resultPopup ref="refCommonPopup" :show-icon="false">
      <template #default="{ result }">
        <view
          style="width: 200rpx"
          class="box-border pl-5rpx mb-30rpx flex-col items-center justify-center text-center w-full"
        >
          <u-form
            ref="refPriceForm"
            :model="priceForm"
            :rules="priceFormRules"
            label-align="left"
            label-position="left"
          >
            <u-form-item prop="customerTypeId">
              <view class="w-full">
                <uni-data-select
                  placeholder="请选择人员类型"
                  v-model="priceForm.customerTypeId"
                  :localdata="customerTypeList"
                  :clear="false"
                ></uni-data-select>
              </view>
            </u-form-item>
            <u-form-item prop="customerCategoryId">
              <view class="w-full">
                <uni-data-select
                  placeholder="请选择客户类别"
                  v-model="priceForm.customerCategoryId"
                  :localdata="customerTypeSmbelList"
                  :clear="false"
                ></uni-data-select>
              </view>
            </u-form-item>
            <u-form-item prop="cardType">
              <view class="w-full">
                <uni-data-select
                  placeholder="请选择卡类别"
                  v-model="priceForm.cardType"
                  :localdata="cardTypeList"
                  :clear="false"
                ></uni-data-select>
              </view>
            </u-form-item>
            <u-form-item prop="price">
              <view class="w-full">
                <u-input type="digit" v-model="priceForm.price" placeholder="请输入价格" clearable />
              </view>
            </u-form-item>
          </u-form>
        </view>
      </template>
      <template #confirm="{ config }">
        <view class="btns-bar">
          <view class="btns-item" @click="refCommonPopup.close('cancel')">
            <text class="btns-item-txt"> 取消 </text>
          </view>
          <view class="btns-item confirm" @click="onPriceConfirm">
            <text class="btns-item-txt"> 确定 </text>
          </view>
        </view>
      </template>
    </resultPopup>

    <!-- 菜品模板弹窗 -->
    <dishesTemplatePopup ref="refDishesTemplatePopup" @select="onSelectTemplate"></dishesTemplatePopup>
  </view>
</template>
<script setup>
import { formatDictData, formatMoney, getFieldValueByDatacom, loadSysDict, splitStrToArray } from "@/utils/util";
import { reactive, ref, computed, onMounted } from "vue";
import {
  foodAdd,
  foodDetails,
  foodEdit,
  getCustomerType,
  getFoolTypeList,
  getCustomerTypeSelect,
  uploadFile,
} from "@/api";
import { onLoad, onReady } from "@dcloudio/uni-app";
import { useStore } from "vuex";
import resultPopup from "@/components/common-popup/result-popup.vue";
import dishesTemplatePopup from "./dishes-template-popup.vue";

const navconfig = reactive({ title: "添加/编辑菜品" });

const pageStatus = reactive({
  loading: false,
});

const uploadFileList = reactive([]);
const delImg = (index) => {
  uploadFileList.splice(index, 1);
};
const afterRead = (e) => {
  console.log("afterRead>", e, uploadFileList);
  e.file.status = "uploading";
  e.file.message = "上传中";
  uploadFileList.push(e.file);

  uploadFile(e.file).then((file) => {
    console.log("uploadFile file >", file);
    const findIndex = uploadFileList.findIndex((v) => v.url == e.file.url);
    if (file) {
      console.log("uploadFileList file >", uploadFileList);
      formData.photo = file.url;
      if (findIndex > -1) {
        uploadFileList.splice(findIndex, 1, {
          ...file,
          status: "success",
          message: "",
          url: file.url,
        });
      }
    } else {
      if (findIndex > -1) {
        uploadFileList.splice(findIndex, 1, {
          ...e.file,
          status: "failed",
          message: "上传失败",
        });
      }
    }
  });
};

const dataSource = {
  yeasOrNo: [
    {
      label: "是",
      value: "1",
    },
    {
      label: "否",
      value: "2",
    },
  ],
};

const store = useStore();

// 表单
const formData = reactive({
  /** 原料list */
  materialRecipeLevelEntityList: [],
  /** 特殊价格 */
  priceItem: [],
  frontDeskPrinting: "1" /** 前台打印 */,
  rearKitchenPrinting: "1" /** 后台打印 */,
  recommend: "2" /** 是否推荐 */,
  memberDiscount: "1" /** 是否会员折扣 */,
  // 基础提交数据
  baseLevel: 2,
  businessId: store.getters.userInfo.id,
  // businessName: store.getters.userInfo.name,
  dataType: 2 /** 	类型（1食物类别2食物） */,
  introcetion: "",
  photo: "",
  parentId: "",
  flavor: "",
  mealtype: "",
  menuId: "",
  name: "",
  totalStars: 0,
  texture: "",
  typeStatus: "1" /* 数据来源(1餐饮 2日照机构) */,
  foodTypeId: "",
  foodTypeName: "",
  price: "",
  effect: "", // 功效
  cookingMethods: "", // 烹饪方法
  unit: "", // 单位
});

const selectType = (e) => {
  console.log("selectType>", e);
  // 找到这个id的项
  const item = foodTypeList.value.find((v) => v.foodTypeId == e);
  if (item) {
    formData.parentId = item.foodTypeId;
    formData.foodTypeName = item.name;
    console.log("formData.parentId", formData.parentId);
  }
};

// 表单规则
const formRules = {
  foodTypeName: {
    required: true,
    message: "请选择类别",
    trigger: ["blur", "change"],
  },
  name: {
    required: true,
    message: "请输入名称",
    trigger: ["blur", "change"],
  },
  price: {
    required: true,
    message: "请输入价格",
    trigger: ["blur", "change"],
    pattern: /^\d+(\.\d+)?$/,
  },
};

const refForm = ref();

onReady(() => {
  refForm.value.setRules(formRules);
});

const getPageData = async () => {
  try {
    const pam = {
      foodTypeId: pageData.id,
    };
    const { data, success } = await foodDetails(pam);
    if (!success) throw new Error("获取数据失败");
    Object.assign(formData, data);

    if (data.photo) {
      uploadFileList.splice(0, uploadFileList.length, { url: data.photo, status: "success" });
    }
  } catch (error) {
    console.error(error);
  }
};

// 菜品分类列表
const foodTypeList = ref([]);

const getTypeList = async () => {
  try {
    const pam = {
      parentId: 0,
      dataType: 1,
      typeStatus: 1,
    };
    const { data, success } = await getFoolTypeList(pam);
    if (!success) throw new Error("获取数据失败");
    const netData = data.map((v) => ({ ...v, text: v.name, value: v.foodTypeId }));
    foodTypeList.value = [/* { text: "全部", value: "" }, */ ...netData];
    // console.log("getTypeList>>", data);
  } catch (error) {
    console.log(error);
  }
};

// 表格原料数据汇总
const totalData = computed(() => {
  const total = {
    totalHeat: 0,
    totalProtein: 0,
    totalFat: 0,
    totalCarbohydrate: 0,
  };
  formData.materialRecipeLevelEntityList.forEach((item) => {
    total.totalHeat += Number(item.quantityHeat) || 0;
    total.totalProtein += Number(item.protein) || 0;
    total.totalFat += Number(item.fat) || 0;
    total.totalCarbohydrate += Number(item.carbohydrate) || 0;
  });
  return total;
});

// 添加原料
const onAddSource = (data) => {
  let haveRepeat = false;
  // 去重插入 formData.materialRecipeLevelEntityList
  for (const v of data) {
    if (!formData.materialRecipeLevelEntityList.find((v1) => v1.materialRecipeLevelId == v.materialRecipeLevelId)) {
      formData.materialRecipeLevelEntityList.push(v);
    } else {
      haveRepeat = true;
    }
  }
  if (haveRepeat) {
    uni.showToast({ title: "添加完成, 已忽略存在的相同原料", icon: "none" });
  }
};

// 删除原料
const delSource = (item, index) => {
  formData.materialRecipeLevelEntityList.splice(index, 1);
};

const pageData = {
  id: "", // 传递的id
  mode: "add", // 传递的模式
};

// 类字典 - 人员类型
const customerTypeList = ref([]);
const customerType = async () => {
  try {
    const pam = { dataType: 1 };
    const { data, success } = await getCustomerType(pam);
    if (data) {
      customerTypeList.value = data.map((v) => {
        return { text: v.typeName, value: v.customerInformationTypeId };
      });
    }
  } catch (error) {
    console.error("获取客户类型失败: " + error.message);
  }
};

// 类字典 - 客户类别
const customerTypeSmbelList = ref([]);
const customerTypeSmbel = async () => {
  try {
    const pam = { dataType: 8 };
    const { data, success } = await getCustomerTypeSelect(pam);
    if (data) {
      customerTypeSmbelList.value = data.map((v) => {
        return { text: v.typeName, value: v.customerInformationTypeId };
      });
    }
  } catch (error) {
    console.error("获取客户类型失败: " + error.message);
  }
};
customerTypeSmbel();

// 类字典 - 卡类型
const cardTypeList = ref([
  { text: "会员卡", value: "1" },
  { text: "套餐卡", value: "2" },
]);

const dicts = reactive({
  sys_tabooPopulation: [],
  sys_flavor: [],
  sys_texture: [],
  sys_spicy: [],
  sys_unit_food: [],
  sys_cookingMethods_food: [],
  sys_effect_food: [],
});

customerType();

onLoad(async (opt) => {
  if (opt.id) pageData.id = opt.id;

  pageData.mode = opt.mode;
  if (pageData.mode == "edit" && pageData.id) {
    navconfig.title = "编辑菜品";
    getPageData();
  } else {
    navconfig.title = "添加菜品";
  }

  try {
    /** 字典 */
    await loadSysDict([
      "sys_tabooPopulation",
      "sys_flavor",
      "sys_texture",
      "sys_texture",
      "sys_spicy",
      "sys_unit_food",
      "sys_cookingMethods_food",
      "sys_effect_food",
    ]);
    const dictSource = store.getters["dicts/getDictSource"];
    Object.assign(dicts, dictSource);
    // console.log("onLoad >> loadSysDict", dicts);
  } catch (error) {
    console.warn("ERROE >> ", error);
  }

  // 获取菜品分类列表
  getTypeList();
});

const hasTaboo = computed(() => {
  return (tabooValue) => {
    if (!formData.tabooPopulation) return false;
    return formData.tabooPopulation?.includes(tabooValue) ? true : false;
  };
});

// 打开原料选择
const refSelectPopup = ref();
const showPopup = () => {
  refSelectPopup.value.open();
};

// 保存 / 修改 数据
const confirmData = async () => {
  try {
    try {
      // 先验证表单
      await refForm.value.validate();
      // console.log("66");
    } catch (error) {
      console.error("表单验证失败: ", error);
      throw new Error("请先完成表单填写");
    }

    const modeMapApi = {
      add: foodAdd,
      edit: foodEdit,
    };

    const pam = {
      ...formData,
    };
    const { data, success } = await modeMapApi[pageData.mode](pam);
    if (!success) throw new Error("保存失败");
    else {
      uni.showToast({ title: "保存成功", icon: "success" });
      uni.navigateBack();
    }
  } catch (error) {
    console.error(error);
    uni.showToast({ title: error.message || "保存失败", icon: "none" });
  }
};

const onTabooPopulationChange = (val) => {
  console.log(val);
  formData.tabooPopulation = val.join(",");
};

// 特殊价格
const priceForm = reactive({
  cardType: 1,
  customerCategoryId: "",
  customerTypeId: "",
  customerTypeName: "失能、残疾老年人",
  price: "",
});
const priceFormRules = {
  cardType: {
    required: true,
    message: "请选择卡类别",
    trigger: ["blur", "change"],
  },
  customerCategoryId: {
    required: true,
    message: "请选择人员类型",
    trigger: ["blur", "change"],
  },
  customerTypeId: {
    required: true,
    message: "请选择客户类别",
    trigger: ["blur", "change"],
  },
  price: {
    required: true,
    message: "请输入价格",
    trigger: ["blur", "change"],
    // 正则表达式，匹配正整数和小数
    pattern: /^\d+(\.\d+)?$/, 
  },
};

// 删除特殊价格
const delPrice = (item, index) => {
  formData.priceItem.splice(index, 1);
};

const refCommonPopup = ref();
const refPriceForm = ref();
const showPricePopup = () => {
  refCommonPopup.value.open({
    title: "优惠价格设置",
    autoClose: false,
  });

  nextTick(() => {
    // 设置rule
    refPriceForm.value.setRules(priceFormRules);
  });
};

const onPriceConfirm = async () => {
  try {
    await refPriceForm.value.validate();
    // console.log("priceForm.value:", priceForm);
    // 记得使用 ...解构再push, 否则会带有引用传递
    formData.priceItem.push({ ...priceForm });
    refCommonPopup.value.close();
  } catch (error) {
    console.log(error);
  }
};

/** 菜品模板 */
const refDishesTemplatePopup = ref();

const openDishesTemplatePopup = () => {
  refDishesTemplatePopup.value.open({
    autoClose: false,
    title: "选择菜品模板",
  });
};

const onSelectTemplate = (item) => {
  console.log("onSelectTemplate", item);
  formData.recommend = item.recommend || "2"; // 是否推荐
  formData.memberDiscount = item.memberDiscount || "1";
  formData.introcetion = item.introcetion || "";
  formData.photo = item.photo || "";
  formData.parentId = item.parentId || "";
  formData.flavor = item.flavor || "";
  formData.mealtype = item.mealtype || "";
  formData.menuId = item.menuId || "";
  formData.name = item.name || "";
  formData.texture = item.texture || "";
  formData.foodTypeId = item.foodTypeId || "";
  formData.foodTypeName = item.foodTypeName || "";
  formData.price = item.price || "";
  formData.tabooPopulation = item.tabooPopulation || "";

  formData.effect = item.effect || "";
  formData.cookingMethods = item.cookingMethods || "";
  formData.unit = item.unit || "";

  formData.materialRecipeLevelEntityList = item.materialRecipeLevelEntityList || [];
  formData.priceItem = item.priceItem || [];

  // 特殊数据处理
  if (item.photo) {
    uploadFileList.splice(0, uploadFileList.length, {
      url: item.photo,
      status: "success",
      message: "",
    });
  }
  //  Object.assign(formData, item);
};
</script>
<style lang="scss" scoped>
.content {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;

  ::v-deep .u-search__content__icon {
    display: none;
  }

  ::v-deep .u-upload__wrap {
    justify-content: center;
    align-items: center;
  }

  ::v-deep .u-upload__button {
    margin: 0;
  }

  ::v-deep .u-form-item {
    flex: 1;
    justify-content: center;
    min-height: 40rpx;

    .u-form-item__body__left {
      margin-bottom: 10rpx !important;
    }

    .u-radio,
    .u-checkbox-label--left {
      margin-right: 10rpx;
    }

    .u-checkbox__icon-wrap--disabled--checked,
    .u-radio__icon-wrap--disabled--checked {
      border-color: var(--kui-color-theme) !important;
      background: var(--kui-color-theme-light) !important;
    }
  }

  .total-bar {
    background: linear-gradient(45deg, var(--kui-color-theme-light), transparent);
    padding: 5rpx 10rpx;
    border-radius: 2rpx;
    color: rgb(94, 94, 94);
    position: relative;
    padding-left: 20rpx;
    &::before {
      position: absolute;
      left: 5rpx;
      top: 0;
      content: "";
      background-color: white;
      width: 3rpx;
      height: 100%;
    }
  }

  .form-item {
    margin-right: 50rpx;
    flex: 1;

    &.flex-none {
      flex: none;
    }
  }
}

@import url("@/components/common-popup/btns.scss");
</style>
